package com.buba.util;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet工具类：将get请求和post请求整合到一起
 */
public abstract class BaseServlet extends HttpServlet {
    /**
     * 自定义方法，整合doGet和doPost都将调用方法，方法的内容由子类去实现
     * @param request
     * @param response
     */
    public abstract void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-type","text/html;charset=UTF-8");
        doRequest(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-type","text/html;charset=UTF-8");
        doRequest(request,response);
    }

    /**
     * 统一的获取参数
     * @return
     */
    public Map<String,String> getParam(HttpServletRequest request){
        //获取浏览器传递的参数
        Map<String, String[]> map = request.getParameterMap();
        //创建一个新的容器
        Map<String,String> paramMap = new HashMap<>();
        //遍历将原本map的key，value导入到paramMap中，并减value的数组转为String
        map.forEach((key,value)->{
            paramMap.put(key,value[0]);
        });
        return paramMap;
    }
}
